package com.egao.common.component.hubei.api;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.asymmetric.*;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.egao.common.component.hubei.HuBeiConstants;
import com.egao.common.component.hubei.dto.HuBeiCompanyDTO;
import com.egao.common.component.hubei.dto.HuBeiJobDTO;
import com.egao.common.component.hubei.dto.HuBeiJobsDTO;
import com.egao.common.component.hubei.dto.HuBeiRecruitDTO;
import com.egao.common.core.Constants;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.Position;
import com.egao.common.module.company.entity.Recruit;

import javax.crypto.Cipher;
import java.math.BigDecimal;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 * 湖北省24365数据上报接口
 *
 * @author lym
 * @date 2024/7/29 14:06
 */
public class HuBeiApi {

    /**
     * 省参数ID
     */
    private final static String ID = "ZUEL16503FF1CD039E";
    /**
     * 省参数KEY
     */
    private final static String KEY = "F17F14B7A86B998B94F56F4D25E73793";
    /**
     * 省参数PUBLIC_KEY
     */
    private final static String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnLLOc/vYFWZz2BUlr7H80PSbz/J8qgdouJU3N5WnehrRyaYf5WHvxysvGt2uz+PQ8zBx6u2mVTOC/kraoocpSepAkfVSgghyNHYuNwJ7b7AQXvtcJ6X7/RwupVbn6aYdUk9Rn24K6+/4+uJHPWcBEDZyXnlhqTyCU+0YxoXQtsEG4XrrKMCyHMYOIlthl7Uw1PSJIh/wCC7bLalRnsnYbIv5kOyIzwFClq2DT3sKOCl80HmN9uL1g/BjIFlwpxVmSji28+BVT3WryapzOJCDIm8pYOaVaOgDIFi3tbpgLK5znAbndpj7X8MBo3b0I3qhL7eVVSET+u4/e0cZhqtZKwIDAQAB";
    /**
     * 省参数PRIVATE_KEY
     */
    private final static String PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCcss5z+9gVZnPYFSWvsfzQ9JvP8nyqB2i4lTc3lad6GtHJph/lYe/HKy8a3a7P49DzMHHq7aZVM4L+StqihylJ6kCR9VKCCHI0di43AntvsBBe+1wnpfv9HC6lVufpph1ST1Gfbgrr7/j64kc9ZwEQNnJeeWGpPIJT7RjGhdC2wQbheusowLIcxg4iW2GXtTDU9IkiH/AILtstqVGeydhsi/mQ7IjPAUKWrYNPewo4KXzQeY324vWD8GMgWXCnFWZKOLbz4FVPdavJqnM4kIMibylg5pVo6AMgWLe1umAsrnOcBud2mPtfwwGjdvQjeqEvt5VVIRP67j97RxmGq1krAgMBAAECggEBAJhuN/cLnf/zUe15ZNesxMpfqNJ4iFy+KFimjrg7lFdrj3ghahWxV5bfo0r3Kv6AFtr63VYzKALpwRutpVFFOhz1CyrxAfoMTUxLSlmoyHq1QreivNq01JQ7vgSIrcDUHuHa1wPIAEfTgNhNFg/dC2PCEy9j1GTUv9L0aY10zrt3Mmbq81zhTqLgj2vG8nvT6pVipE0WOy1jxfCLi+vIz9UDnC4l9de0wJa6i5U8cutJPSX1Hncz0ypAfWkgOirZ0FUqMXA42qRK3qCBSbgHGlKS5Xr91bZrNjlSmBMV68WhxPK6t10a9cvl+v77ywSCTrHWPp/rGylI+fHhKVZMSIECgYEA3qomYXAwrNCvJ+WLUHGwT5PVfmgNkJiztn2UrGvPtjSVYkTcxRHbhGIvod8d0Si5ya9YdntYQQf+078Pl7DUMugGSKwJAp0+oXgtjqIWHy0WnZ9EpJxDws/hk425+vSNIWGu+yWWWC9yVh5wrz6GCAuHCzqYkY8hSHqB25mtokkCgYEAtChvYoeeRRRjigXatQlWnGgI/2uMozQeg9r1+wnWt8yGcIxFE0GeThOdpHewO1/TxAe1rovyvyg+oMj2sjUbN3/m6WdxQIZwd5edrt7RsgOezUx+T854D7lRAP1AfQJdGDFqCG0T6KV9dLo6PQ4Fc2Dikk2CAgi2TdssH6qp39MCgYA5y6qIsilAQi6kyXU+3TOphDLvS6zxsmE7Zh9YHefdYIrB5iPz1y3GkAHTH2nK56pJyoTIxD1lK+EeL0Kp2hFKYWV4KYdxMUWXfe09T580Wmy7XyLfI1yHTZQ8y5XRqPaVCpjzwY7jtvUTm3UeV7lMj0lvRbdiWOeHu5zHVn12WQKBgQCCglhOVFh/SonhTuRlCWLI40TBY7P59qO0eUaAmVwGwg8SMUtI69w2S1eD8YClQoIyHDOtQoyTlh/ocizkZDxXNDyfEOSmDb4jpJ4CNEBMaPr9VlCal8O6AFGCGfRBmxi9ke5yNDKb8mazzMSrviCMuL7ppWRs/Mq0E/Ye6o8tKQKBgBN38LRNpympMAgfNlBkwZGHMe/jUmCelSfejcW2K+mzByKrvGEiQcbK6wxVyMYOHYL8TKsDy+nMLKkvmMh8bldAE6gNfa16yDP4qGMk3iXDifTdUNkcqp+tiLEyO1lQbClhrOS0uWAUJ5pFUuotU+AnMX+Wb7ea8Kl1tPgA9tW7";


    /**
     * 校验签名获取随机返回值（请求方式POST）
     *
     * @param type 数据类型
     */
    private static JsonResult getSign(String type) {
        String url = "https://www.91wllm.com/service/reportJx/checkSign";

        Map<String, Object> data = new HashMap<>(4);
        data.put("id", ID);
        data.put("key", KEY);
        data.put("type", type);
        data.put("timestamp", System.currentTimeMillis() / 1000);
        String dataStr = JSONUtil.toJsonStr(data);

        try {
            String sign = buildPrivateRsaSign(dataStr);
            if (StrUtil.isBlank(sign)) {
                return JsonResult.error("生成签名失败");
            }

            // 发送请求
            Map<String, Object> params = new HashMap<>(2);
            params.put("data", data);
            params.put("sign", sign);
            String res = HttpUtil.post(url, JSONUtil.toJsonStr(params));

            // 结果解析
            JSONObject jsonObject = JSONUtil.parseObj(res);
            Integer code = jsonObject.getInt("code");
            String msg = jsonObject.getStr("msg");
            if (500 == code) {
                return JsonResult.error("获取签名失败：" + msg);
            }

            if (200 == code) {
                String result = jsonObject.getStr("result");
                return JsonResult.ok().setData(result);
            }

            return JsonResult.error("获取签名失败2：" + msg);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("生成签名错误");
        }
    }

    /**
     * 数据上报
     * @param type 上报类型
     * @param rnum 第一步验证随机数
     * @param dataStr 上报数据集合
     * @return JsonResult
     */
    private static JsonResult report(String type, String rnum, String dataStr) {
        String url = "https://www.91wllm.com/service/reportJx/report";

        Map<String, Object> packageMap = new HashMap<>(5);
        packageMap.put("id", ID);
        packageMap.put("key", KEY);
        packageMap.put("type", type);
        packageMap.put("rnum", rnum);
        packageMap.put("timestamp", System.currentTimeMillis() / 1000);
        String packageStr = JSONUtil.toJsonStr(packageMap);

        String sign = buildPrivateRsaSign(packageStr);
        if (StrUtil.isBlank(sign)) {
            return JsonResult.error("生成签名失败");
        }

        // 偏移量（IV），需要是16字节
        // 创建一个长度为16的字节数组，默认值为0
        byte[] ivBytes = new byte[16];

        byte[] keyBytes = RandomUtil.randomString(16).getBytes();
        String keyEn = Base64.getEncoder().encodeToString(keyBytes);
        String key = buildPublicRsaSign(keyEn);
        if (StrUtil.isBlank(key)) {
            return JsonResult.error("生成KEY公钥密文失败");
        }

        // AES加密
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, keyBytes.clone(), ivBytes.clone());
        String encrypt = aes.encryptBase64(dataStr);

        // 发送请求
        Map<String, Object> params = new HashMap<>(4);
        params.put("package", packageMap);
        params.put("sign", sign);
        params.put("key", key);
        params.put("data", encrypt);
        String res = HttpUtil.post(url, JSONUtil.toJsonStr(params));

        // 结果解析
        JSONObject jsonObject = JSONUtil.parseObj(res);
        Integer code = jsonObject.getInt("code");
        String msg = jsonObject.getStr("msg");
        if (500 == code) {
            return JsonResult.error("数据上报失败：" + msg);
        }

        if (200 == code) {
            return JsonResult.ok("数据上报成功");
        }

        return JsonResult.error("数据上报异常：" + msg);
    }

    /**
     * 生成私钥RSA签名
     * @param data 数据
     * @return 签名字符串
     */
    private static String buildPrivateRsaSign(String data) {
        try {
            // 生成私钥对象
            PrivateKey privateKey = KeyFactory.getInstance(AsymmetricAlgorithm.RSA.getValue()).generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(PRIVATE_KEY)));
            // 签名算法改为SHA1withRSA
            Signature privateSignature = Signature.getInstance(SignAlgorithm.SHA1withRSA.getValue());
            // 生成签名
            privateSignature.initSign(privateKey);
            privateSignature.update(data.getBytes());
            byte[] signature = privateSignature.sign();
            return Base64.getEncoder().encodeToString(signature);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 生成公钥RSA密文
     * @param data 加密前明文
     * @return 加密后密文
     */
    private static String buildPublicRsaSign(String data) {
        try {
            // 生成公钥对象
            PublicKey publicKey = KeyFactory.getInstance(AsymmetricAlgorithm.RSA.getValue()).generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(PUBLIC_KEY)));

            // 加密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedData = cipher.doFinal(data.getBytes());

            // 加密后的数据通常需要进行Base64编码以便于传输
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 上报单位数据
     * @param companyList 单位集合
     * @return JsonResult
     */
    public static JsonResult pushCompany(List<Company> companyList) {
        JsonResult signResult = getSign(HuBeiConstants.TYPE_COMPANY);
        if (Constants.RESULT_ERROR_CODE == signResult.getCode()) {
            return signResult;
        }

        List<HuBeiCompanyDTO> dtoList = new ArrayList<>();
        for (Company company : companyList) {
            HuBeiCompanyDTO dto = new HuBeiCompanyDTO();
            dto.setCompanyid(company.getId());
            dto.setUnified_social_credit_code(company.getOrganizationCode());
            dto.setUsername(company.getName());
            dto.setEmail("346907006@qq.com");
            dto.setIndustry("A01");
            dto.setCity(110000);
            dto.setAddress(company.getAddress());
            dto.setCategory(100);
            dto.setNature(99);
            dto.setScale(100);
            dto.setLinkman(company.getContactName());
            dto.setTelephone(company.getContactMobile());
            dto.setContact("无");
            dto.setCorporation("无");
            dto.setRegister_time(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000)));
            dto.setRegister_fund(new BigDecimal(1.00));
            dto.setDescription(company.getContent());
            dto.setZipcode(company.getZipCode());
            dto.setIs_long_term(0);
            dto.setBusiness_term(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000)));
            dto.setSource_url("https://jyzx.zuel.edu.cn");
            dto.setSource_name("中南财经政法大学就业信息网");
            dto.setDateline(Integer.parseInt(String.valueOf(company.getCreateTime().getTime() / 1000)));
            dtoList.add(dto);
        }

        String dataStr = JSONUtil.toJsonStr(dtoList);
        return report(HuBeiConstants.TYPE_COMPANY, signResult.getData().toString(), dataStr);
    }

    /**
     * 上报职位数据
     * @param positionList 职位集合
     * @return JsonResult
     */
    public static JsonResult pushJob(List<Position> positionList) {
        JsonResult signResult = getSign(HuBeiConstants.TYPE_COMPANY);
        if (Constants.RESULT_ERROR_CODE == signResult.getCode()) {
            return signResult;
        }

        int now = Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000));

        List<HuBeiJobDTO> dtoList = new ArrayList<>();
        for (Position position : positionList) {
            HuBeiJobDTO dto = new HuBeiJobDTO();
            dto.setCompanyid(position.getCompanyId());
            dto.setJobid(position.getId());
            dto.setJobname(position.getName());
            dto.setSkill(100101);
            dto.setCity(990000);
            dto.setAddress(position.getAddress());
            dto.setCategory(100);
            dto.setNum(1);
            dto.setSalary(105);
            dto.setEducation(103);
            dto.setMajor(position.getMajor());
            dto.setValidtime(now);
            dto.setDescription(position.getDuty());
            dto.setLinkman("张三");
            dto.setContact("张三");
            dto.setEmail("346907006@qq.com");
            dto.setSource_url("https://jyzx.zuel.edu.cn");
            dto.setSource_name("中南财经政法大学");
            dto.setDateline(Integer.parseInt(String.valueOf(position.getCreateTime().getTime() / 1000)));
            dtoList.add(dto);
        }

        String dataStr = JSONUtil.toJsonStr(dtoList);
        return report(HuBeiConstants.TYPE_JOB, signResult.getData().toString(), dataStr);
    }

    /**
     * 上报招聘公告数据
     * @param recruitList 招聘信息集合
     * @return JsonResult
     */
    public static JsonResult pushRecruit(List<Recruit> recruitList) {
        JsonResult signResult = getSign(HuBeiConstants.TYPE_COMPANY);
        if (Constants.RESULT_ERROR_CODE == signResult.getCode()) {
            return signResult;
        }

        int now = Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000));

        List<HuBeiRecruitDTO> dtoList = new ArrayList<>();
        for (Recruit recruit : recruitList) {
            HuBeiRecruitDTO dto = new HuBeiRecruitDTO();
            dto.setPid(recruit.getId());
            dto.setCompanyid(recruit.getCompanyId());
            dto.setTitle(recruit.getTitle());
            dto.setCity("990000");
            dto.setCity_zh("国外");
            dto.setValidtime(now);
            dto.setDescription(recruit.getContent());
            dto.setSource_url("https://jyzx.zuel.edu.cn/home/career/internship?id=39700");
            dto.setSource_name("中南财经政法大学");
            dto.setDateline(Integer.parseInt(String.valueOf(recruit.getCreateTime().getTime() / 1000)));

            HuBeiJobsDTO jobsDTO = new HuBeiJobsDTO();
            jobsDTO.setJobid(21160);
            jobsDTO.setJob_name("梦想家");
            jobsDTO.setMajor("哲学");
            jobsDTO.setNums(1);
            jobsDTO.setTreatment(111);
            jobsDTO.setEducation(103);
            jobsDTO.setCategory(100);
            jobsDTO.setSource_url("https://jyzx.zuel.edu.cn");
            List<HuBeiJobsDTO> jobsDTOList = new ArrayList<>();
            jobsDTOList.add(jobsDTO);
            dto.setJobs(jobsDTOList);

            dtoList.add(dto);
        }

        String dataStr = JSONUtil.toJsonStr(dtoList);
        return report(HuBeiConstants.TYPE_CAMPUS, signResult.getData().toString(), dataStr);
    }

}
